 
var mqtt = require('mqtt')
var _this;
var client;
var num = 0;
var username; 
var password;
// 登陆界面状态
var oncelogin = true;
var lodingtime = 0;
var loginval;
var userid;
// 判断是否显示新订单弹框
var dingdanflag = false;


var MQTTconnect = function(this_, val, userid1, user, password1) {
	username = user;
	password = password1;
	_this = this_;
	loginval = val;
	userid = userid1;
	var str = userid1 + ";" + uni.getStorageSync('token') + ";";
	var groupId = 'GID_WENYUE';
	var clientId = groupId + uni.getStorageSync('token');
	var options = {
	  keepalive: 6,
	  clientId: clientId,
	  clean: true,
	  reconnectPeriod: 3000,
	  connectTimeout: 6 * 1000,
	  will: {
	    topic: 'WillMsg',
	    payload: str,
	    qos: 2,
	    retain: false
	  },
	  username: username,
	  password: password
	}
	
	// #ifdef H5
	 client = mqtt.connect('wss://mqtt.suxin88.com:8084/mqtt',options)
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	client = mqtt.connect('wxs://mqtt.suxin88.com:8084/mqtt',options)
	// #endif
	client.on('connect', function() {
		onConnect(val)
	})
	client.on('reconnect', function(data) {
		console.log(data)
		num ++;
		console.log(num)
		if (oncelogin == false &&num == 2) {
			uni.showToast({
				title: '与服务器断开连接，正在重连...',
				icon: "none",
				mask: true,
				duration: 10000000
			})
		}
		if(oncelogin == false && num > 30){
			uni.showToast({
				title: '网络不稳定,请重新登录',
				icon: 'none'
			});
			oncelogin = true;
			uni.reLaunch({
				url: '/pages/login/login'
			});
			cleartimer();
			 client.end()
		}
		console.log('on reconnect');
	})
	client.on('error', function(err) {
		console.log(err);
		if(oncelogin == true && num > 3){
			cleartimer();
			uni.showToast({
				title: '网络不稳定,请稍后重试',
				icon: 'none'
			});
			 client.end()
		}
		console.log(err)
	})
	client.on('end', function() {
		console.log('on end')
	})
	client.on('message', function(topic, message) {
		onMessageArrived(message.toString());
	})
	
	

}
var obj = {

	// 登陆处理
	login: function(arr) {
		lodingtime = 1;
		if (arr[1] == 1) {


			if (oncelogin == true) {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
			if (oncelogin == true || num > 1) {
				uni.showToast({
					title: `${arr[2]}`,
					icon: "none"
				})
			}
			if(oncelogin == false){
				if(uni.getStorageSync('ifjiedan') == 1){
					var data = {
						token: uni.getStorageSync('token')
					};
					_this.$store.dispatch('grapstart', data)
				}
			}
			oncelogin = false; 
			var topic = "ZiJinTZ_" + uni.getStorageSync('token');
			client.subscribe(topic, {
				qos: 2
			});
			var topicn = 'CICHAN_' + uni.getStorageSync('token');
			client.subscribe(topicn, {
				qos: 2
			});
			num = 0;
			uni.hideLoading();


		}
		if (arr[1] == 0) {
			uni.showToast({
				title: arr[2],
				icon: "none"
			})
			client.end();
		}
	},
	order: function(arr) {
		console.log(arr)

		if (arr[1] == 1) {
			console.log(_this.ifindex);
			
			
			_this.$bus.$emit("ordernew",arr)
			if (_this.ifindex == true) {
				var pages = getCurrentPages();

				var page = pages[pages.length - 1];
				console.log(page.route);
				if (page.route != "pages/index/index" && dingdanflag == false) {
					dingdanflag = true;
					uni.showModal({
						content: `有新订单啦,返回首页？`,
						success: function(res) {
							if (res.confirm) {
								_this.$bus.$emit("tabfw", 1)
								uni.switchTab({
									url: '/pages/index/index'
								});
							} else if (res.cancel) {
								_this.$store.commit("ifindex", false)
								console.log('用户点击取消');
							}
						}
					});

				} else {
					dingdanflag = false;
				}
			}
			
			if (uni.getStorageSync('is_auto') * 1 == 1) {
				var data = {
					token: uni.getStorageSync('token'),
					order_id: arr[2]
				};
				_this.$store.dispatch('takeorder', data).then(res => {

					if (res.data.code == 1) {
						var data = {
							token: uni.getStorageSync('token'),
						};
						_this.$store.dispatch('orderunderway', data)
					}
				});
			}

			_this.$store.commit("orderadd", arr)

		}

	},
	startorder: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
		if (arr[1] == 1) {
			_this.$bus.$emit("ifstart", false)
		}
	},
	stoporder: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
		if (arr[1] == 1) {
			_this.$bus.$emit("ifstart", true)
		}
	},
	heart: function(arr) {
		
		if (arr[1] == 1) {
			heartflag = 1;
		}
	},
	qiangxx: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
	},
	assets: function(arr) {

		_this.$store.commit("assetsupdate", arr)
	},
	// 重复登陆
	reLogin: function(arr) {

		closeConnect();
		uni.showModal({
			title: '登陆过期',
			content: `您的帐号已在异地登陆,如果非本人操作请尽快修改密码!`,
			showCancel: false,
			success: function(res) {
				closeConnect();
				uni.removeStorage({
					key: 'password',
					success: function(res) {

					}
				});
				cleartimer();
				
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		});
	},
}
function cleartimer(){
	_this.$bus.$emit("cleartimer", 1)
	_this.$bus.$emit("cleartimer1", 1)
	
	_this.$bus.$emit("cleartimern", 1);
	_this.$bus.$emit("cleartimerq", 1);
}
function onMessageArrived(message) {

	var arr = [];
	arr = message.split(";");

	switch (arr[0] * 1) {
		case 1:
			obj.order(arr);
			break;
		case 2:
			obj.assets(arr);
			break;
		case 20:
			obj.login(arr);
			break;
		case 21:
			obj.startorder(arr);
			break;
		case 22:
			obj.stoporder(arr);
			break;
		case 23:
			obj.qiangxx(arr);
			break;
		case 51:
			obj.reLogin(arr);
			break;
		case 50:
			obj.heart(arr);
			break;
	}


}

function onConnect(val) { //连接成功
	console.log("连接成功")
	//订阅消息
	lodingtime = 0;
    var topic = "login_" + uni.getStorageSync('token');
   
	client.subscribe(topic, { qos: 2 })
	console.log('on connect')
	client.publish('login_req', val)
	
	//解决服务器连接，webshock无返回问题
	setTimeout(() => {
		if (lodingtime == 0) {

			closeConnect();
			oncelogin = true;
			uni.reLaunch({
				url: '/pages/login/login'
			});
			var data = {
				token: uni.getStorageSync('token')
			}
			_this.$store.dispatch("logout", data)
			cleartimer();
			uni.showToast({
				title: "网络不稳定，请重新登录",
				icon: "none"
			})

		}
	}, 5000)


}


function closeConnect() {
	oncelogin = true;
	cleartimer();
	client.end();
	
}

function sendmsg(topic, val) {
	client.publish(topic, val)
	// console.log(topic, val)
}
export {
	MQTTconnect,
	closeConnect,
	sendmsg
};
